package com.zjh.photoshopstudy.app.upload;

import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;

import com.zjh.photoshopstudy.Model.AppUserEntity;
import com.zjh.photoshopstudy.Model.VideoEntity;
import com.zjh.photoshopstudy.Utils.SharePreferencesUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class UploadPresent {
    UploadActivity activity;
    UploadHttp http;

    public UploadPresent(UploadActivity activity) {
        this.activity = activity;
        this.http = new UploadHttp();
    }

    public void upload(VideoEntity videoEntity, List<Uri> uriList, List linkList) {
        AppUserEntity entity = SharePreferencesUtils.getLoginUser(activity);
        AppUserEntity user = new AppUserEntity();
        user.setId(entity.getId());
        videoEntity.setvAppUserEntity(user);
        File[] files = new File[uriList.size()];
        List<String> list = new ArrayList<>();
        for (int i = 0; i < files.length; i++) {
            if (i == 2) {
                String path = uriList.get(i).getPath();
                files[i] = new File(path);
                continue;
            }
            try (Cursor cursor = activity.getContentResolver().query(uriList.get(i), null, null, null, null)) {
                cursor.moveToNext();
                String path = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA));
                files[i] = new File(path);
                if (i >= 3) {
                    list.add(files[i].getName());
                }
            }
        }

        String text = videoEntity.getvContent();
        text = getResume(list, text, "查看图片 ");
        text = getResume(linkList, text, "打开链接 ");
        videoEntity.setvContent(text);
        http.upload(videoEntity, files);
    }

    private String getResume(List uriList, String text, String s) {
        int index = 0;
        while (text.contains(s)) {
            String temp;
            if (s.equals("查看图片 ")) {
                temp = "<i>" + uriList.get(index).toString() + "</i>";

            } else {
                temp = "<link>" + uriList.get(index).toString() + "</link>";
            }
            index++;
            text = text.replaceFirst(s, temp);
        }
        return text;
    }
}
